package com.pj.common.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.pj.common.R
import com.pj.common.annotation.LayoutParam
import com.pj.common.extension.MsgEvent
import com.pj.common.utils.CommonUtils
import com.qmuiteam.qmui.widget.QMUIEmptyView
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseActivity<VM : BaseViewModel, VB : ViewDataBinding> : AppCompatActivity() {
    protected lateinit var mBinding: VB
    protected lateinit var mViewModel: VM
    var tipDialog: QMUITipDialog? = null
    var emptyView: QMUIEmptyView?  = null

    /**
     *
     * @return 布局ID
     */
    abstract fun getLayoutRes(): Int

    //protected lateinit var mViewModel: BaseViewModel
    open fun initBefore() {}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initBefore()
//        mBinding = DataBindingUtil.setContentView(this,getLayoutRes())
        initLayout()
        initData(savedInstanceState)
        uiObserve()
    }

    private fun initLayout() {
        mBinding = DataBindingUtil.inflate(layoutInflater, getLayoutRes(),null,false)
        setContentView(mBinding.root)
        mBinding.lifecycleOwner = this
        val tp = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        mViewModel =
            ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(tp as Class<VM>)
        lifecycle.addObserver(mViewModel)
    }

    protected fun createBinding(clz: Class<Any>): Int {
        var activityParam: LayoutParam? = CommonUtils.findAnnotation(clz)
        if (activityParam == null) {
            throw IllegalArgumentException("BaseActivity master has BaseActivityParam,and the param layout must not null!")
        }
        return activityParam.layout
    }

    protected open fun initData(savedInstanceState: Bundle?) {
        tipDialog = QMUITipDialog.Builder(this)
            .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
            .setTipWord("正在加载")
            .create()
    }

    protected open fun uiObserve() {
        emptyView = findViewById(R.id.empty_view)
        mViewModel.uiEmpty.observe(this) {

        }
        mViewModel.uiLoading.observe(this) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
        mViewModel.msgEvent.observe(this) {
            messageEvent(it)
        }
    }

    protected open fun messageEvent(msg: MsgEvent) {

    }

    fun emptyView(v: QMUIEmptyView) {
        emptyView = v
    }

    fun showLoading() {
        tipDialog?.show()
    }

    fun hideLoading() {
        tipDialog?.hide()
    }

}